<template>
	<page>
	<!-- <view>
		<view >
			<view>
				<view class='header'>
					<image src='../../static/small2_avatar.png'></image>
				</view>
				<view class='content'>
					<view>申请获取以下权限</view>
					<text>获得你的公开信息(昵称，头像、地区等)</text>
				</view>

				<button class='bottom' type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">
					授权登录
				</button>
			</view>
		</view>
	</view> -->
	<view class='container'>
	  <view class='login_box'>
	    <image src='../../static/small2_avatar.png'></image>
	    <text class='font-15 mgt-5'>同城共享装修</text>
	  </view>
	  <view class='center_box'>
	    <view class='box_one'>
	      <view>
	        <text class='font-15'>请允许同城共享装修获取以下权限</text>
	      </view>
	      <view>
	        <text class='font-13 font-normal'>以下信息仅用于您登录同城共享装修，我们将严格不外泄，更不会对您发送垃圾信息造成骚扰</text>
	      </view>
	    </view>
	    <view class='box_two mgt-20'>
	      <view v-if="is_show">
	        <text class='font-15 login_active'>获取您的公开信息（昵称，头像等）  </text>
	      </view>
	      <view v-else>
	        <text class='font-15 '> 获取您的公开信息（昵称，头像等）</text>
	      </view>
	      <view>
	        <text class='font-13 font-normal'>获取您的公开信息方便您使用全部功能</text>
	      </view>
	    </view>
	    <view class='box_three mgt-20'>
	      <view v-if="is_show">
	        <text class='font-15'>授权手机号成功  </text>
	      </view>
	      <view v-else>
	        <text class='font-15 login_active'>授权手机号成功  </text>
	      </view>
	      <view>
	        <text class='font-13 font-normal'>获取您的手机号用于实名认证</text>
	      </view>
	    </view>
	  </view>
	  <view class='footer_btn'>
	    <button id='1' class='submit-btn submit-margin-top font-18 botCenterButton' hover-class v-if="is_show" open-type='getUserInfo' @getuserinfo='bindGetUserInfo'>第一步 ，授权公开信息</button>
	    <button id='1' class='submit-btn submit-margin-top font-18 botCenterButton' hover-class v-else open-type='getPhoneNumber' @getphonenumber='getPhoneNumber'>第二步，授权手机号</button>
	  </view>
	</view>
	</page>
</template>

<script>
	import app from '@/App.vue';
	import {
		GYZJMODEL as gyzjModel
	} from '@/utils/gyzjModel.js'
	export default {
		data() {
			return {
				// SessionKey: '',
				// OpenId: '',
				// nickName: null,
				// avatarUrl: null,
				// inviteCode:"",
				token:'',
				is_show:true,
				userInfo: '',
			};
		},
		onLaunch() {
			console.log('剛開始登錄的方法啊');
			/*微信小程序,帶邀請碼*/
			// #ifdef MP-WEIXIN
			let that=this,inviteCode='';
			if(options.query.inviteCode!=undefined){
				inviteCode=options.query.inviteCode||'';
			}
			if(options){
				var scene=decodeURIComponent(options.query.scene);
				if(scene!='undefined'){
					inviteCode=scene;
				}
			}
			// #endif
		},
		onLoad() {
			this.login().then(res=>{
				console.log('onLoad获取的res的值',res);
				let token=encodeURIComponent(res.data.token);
				app.globalData.token=token;
				uni.setStorageSync('token',token);
				// #ifdef MP-WEIXIN
				if(this.tokenReadyCallback){
					this.tokenReadyCallback();
				}
				// #endif
				//获取userInfo
				this.getUserInfo(token,1);
			}).then(res=>{
				console.log('后一步获取用户信息');
			}).then(message=>{
				console.log('执行message');
			}).catch(error=>{
				 console.log("执行promise时，出现了错误",error);
			});
		},
		methods: {
			// 发起手机授权
			  getPhoneNumber(e) {
			    let _this = this;
				//无论用户拒绝允许手机号都跳首页
			    if (e.detail.errMsg == 'getPhoneNumber:ok') {
			      _this.decodePhone(e);
				  uni.reLaunch({
				  	url:'../index/index'
				  })
			    } else {
			      this.closePhone();
				  uni.reLaunch({
				  	url:'../index/index'
				  })
			    }
			  },
			  // 获取手机号
			    decodePhone(e) {
			      let _this = this;
			      let token = uni.getStorageSync("token");
			      let postData = {
			        iv: e.detail.iv,
			        encryptedData: e.detail.encryptedData,
			        sessionKey: decodeURIComponent(token)
			      }
			      gyzjModel.prototype.decryptPhone(postData).then(data => {
			        uni.showLoading();
			        switch (data.code) {
			          case 1:
			            console.log('执行成功获取的手机号码',data);
			            console.log(data);
						let postDataMobile={
							mobile:data.data.phoneNumber
						}
						console.log('授权成功的手机号值',postDataMobile);
			            _this.updateUserInfoFunc(token,postDataMobile,1);
			            break;
			          default:
			            uni.hideLoading();
			            uni.showToast({
			              title: data.message,
			              icon: 'none'
			            })
			            break;
			        }
			        uni.hideLoading();
			      })
			  
			    },
			   closePhone() {
			      if (app.globalData.query && app.globalData.query.type == 'jiazhang') {
			        
			      }else{
			        uni.navigateTo({ //没有获取到手机号码跳转地址
			          url: '../index/index',
			        })
			      }
			     
			    },
			//登录
			login() {
				// 1.wx获取登录用户code
				return new Promise((resolve,reject)=>{
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {
							console.log('微信登录aa');
							let postData={
								code:loginRes.code,
								inviteCode:'',
							}
							resolve(gyzjModel.prototype.userLogin(postData));
						},
					});
				})
			},
			bindGetUserInfo:function(e){
				//用户拒绝授权
				if (e.detail.errMsg.indexOf("getUserInfo:fail") >= 0) {
					console.log('执行了拒绝授权');
				  uni.hideLoading();
				  //拒绝用户信息，没得说，回到上一页
				  uni.navigateBack({});
				  return;
				};
				let _this = this;
				uni.getUserInfo({
					provider: 'weixin',
					success: function(infoRes) {
						console.log('infoRes', infoRes);
						 //真实姓名默认设置为用户昵称
						e.detail.userInfo.name = e.detail.userInfo.nickName;
						let token=uni.getStorageSync('token');
						/*如果获取了昵称,那么存在全局手机号需要删除*/
						if(app.globalData.mobile){
							console.log('删除了全局mobile',app.globalData.mobile);
							app.globalData.mobile='';
						}
						_this.updateUserInfoFunc(token,e.detail.userInfo,1);
					}
				});
			},
			updateUserInfoFunc:function(token,e,type){
				gyzjModel.prototype.updataUserInfo(token,e,type).then(data=>{
					switch (data.code) {
						case 1:
							/*获取数据自动更新全局*/
							this.getUserInfo(token,type);
							/*设置值*/
							this.is_show=false;
							break;
						default:
							uni.showToast({
								title: data.message,
								icon: 'none',
							})
					}
					uni.hideLoading();
				})
			},
			//第一次自动授权或多次重复获取（更新)用户信息，存储起来,可以在用户访问了这里直接给他微信的数据
			getUserInfo(token,type) {
				return new Promise((resolve,reject)=>{
					gyzjModel.prototype.getUserInfo(token,type).then(res=>{
						console.log('获取用户的res的值',res);
						app.globalData.userInfo=res.data.user;
						console.log('设置了全局的globalData',app.globalData);
						console.log('设置了globalData的值为',app.globalData.userInfo);
						uni.setStorageSync('userInfo',app.globalData.userInfo);
						//判断用户信息这些
						// #ifdef MP-WEIXIN
						if (this.userInfoReadyCallback) {
						  this.userInfoReadyCallback(res)
						}
						// #endif
						uni.hideLoading();
					})
				})
			},
			/*设置一个jump函数判断跳转*/
			  jump: function(){
			    if (app.globalData.query && this.globalData.query.type) {
			      console.log('如果是分享带参数的处理')
			      uni.reLaunch({
			        url: '/pages/index/index',
			      })
			    } else {
			      console.log('分享不带参数的处理')
			    }
			  },
		},
	}
</script>

<style>
	/* .header {
		margin: 90upx 0 90upx 50upx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650upx;
		height: 300upx;
		line-height: 450upx;
	}

	.header image {
		width: 200upx;
		height: 200upx;
	}

	.content {
		margin-left: 50upx;
		margin-bottom: 90upx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40upx;
	}

	.bottom {
		border-radius: 80upx;
		margin: 70upx 50upx;
		font-size: 35upx;
	} */
	.container{
	  padding:70upx 30upx 0upx 30upx;
	}
	.login_box{
	  display:flex;
	  flex-direction:column;
	   margin:0upx auto;
	   align-items:center;
	}
	.login_box image{
	   height:140upx;
	  width:140upx;
	}
	.center_box{
	  margin-top:100upx;
	}
	.login_active{
	   color:#09BB07!important;
	   font-weight:bold;
	}
	/*按钮*/
	.submit-btn{
	  background-color:#09BB07;
	  margin-top:172upx;
	  width:100%;
	  color: #fff;

	}
	.mgt-20 {
		margin-top: 40upx !important;
	}
	.font-15 {
	font-size: 30upx !important;
	}
	.font-18 {
	font-size: 36upx !important;
	}
	.font-13 {
	font-size: 26upx !important;
	}
	.font-normal {
	color: #666 !important;

	}
	.login_active {
	color: #09BB07!important;
	font-weight: bold;
	}



</style>
